<template>
	<view>
		<view>
			<u-navbar  :is-back="true"  back-icon-color="#ffffff" :border-bottom="false"
					   title="AI会话" title-color="#ffffff" title-bold  :title-size="34"
					  :background="{backgroundColor:'none'}">
				<view slot="right" class="u-m-r-30">
					<view @click="clear(null)">
						<!-- :disabled="messageList.length<1" -->
						<u-icon name="reload" size="50" color="#ffffff"></u-icon>
						<!-- 	<u-icon name="yanqi" custom-prefix="custom-icon" size="44" color="#ffffff"></u-icon> -->
					</view>
				</view>
			</u-navbar>
		</view>
		<view style="position: fixed;z-index: 1000;width: 100%;">
			<u-notice-bar  padding="20rpx 24rpx"  type="warning" height="80" bg-color="none"
							:list="notice"></u-notice-bar>	
		</view>
		<view>
			<view class="msg-container">
				<scroll-view :scroll-y="true" class="msg-box-scroller  hidden-scroll-bar"
					:style="'height:'+scrollViewHeight+'px'" 
					:scroll-into-view="scrollIntoView" 
					:scroll-top="scrollTop"
					 :scroll-with-animation="scrollAnimation"
					@scrolltoupper="$noClicks(loadMoreHistoryMsg)" 
					:upper-threshold="10" 
					@touchstart="hideDrawer">
					<view style="width: 100%;" v-for="(item,index) in messageList" 
								:key="index">
						<view>
							<view class="chat-time">
								<text v-if="item.createTime.length&&item.showTimeFlag">
									{{item.createTime.substring(10,16)}}
								</text>
							</view>
							<view :class="{'chat-user-name':true,'chat-location-me':item.meFlag}">
								<text>{{item.userName}}</text>
							</view>
							<view :class="{'chat-container':true,'chat-location-me':item.meFlag}">
								<view class="chat-icon-container">
									<image :class="{'chat-icon':true,'chat-icon-me':item.meFlag}"
										:src="item.userAvatar?item.userAvatar:'/static/image/default/default-user/default-user.png'"
										mode="aspectFill" />
								</view>
								<view class="chat-content-container u-p-t-10" @longpress="showToolTip($event,index)">
									<view :id="'msg_'+item.id">
										<view :class="{'chat-text-container':true,'chat-text-container-me u-text-reserve':item.meFlag}">
											<u-parse :html="parseTextContent(item)"  :tag-style="tagStyle">
											</u-parse>
										</view>
									</view>
								</view>
							</view>
						</view>		
					</view>
					<view v-if="waiting==true">
						<view class="chat-user-name">
							<text>AI-007</text>
						</view>
						<view class="chat-container">
							<view class="chat-icon-container">
								<image class="chat-icon" src="https://img.api.aa1.cn/2023/02/12/59c6fee6f7e66.png"
									mode="aspectFill" />
							</view>
							<view class="chat-content-container u-p-t-10">
								<view :id="'msg_'+(currentAIAnswer.length-1)">
									<view class="chat-text-container">
										<view style="width: 100%;" class="u-flex u-row-center u-col-center">
											<text  v-if="currentAIAnswer.length<1">AI思考中</text>
											<u-loading  mode="flower" size="38"></u-loading>
										</view>
										<view v-if="currentAIAnswer.length>0">
											<text>{{currentAIAnswer}}</text>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
			<view class="footer-container">
				<view class="input-box">
					<view class="input-box-flex">
						<!-- 语音/键盘切换,H5不支持 -->
						<!-- #ifdef APP-PLUS -->
						<view>
							<image v-if="chatType === 'voice'" class="icon_img"
								:src="require('@/static/image/chat/voice/voice.png')" @click="switchChatType('keyboard')">
							</image>
							<image v-if="chatType === 'keyboard'" class="icon_img"
								:src="require('@/static/image/chat/keyboard.png')" @click="switchChatType('voice')">
							</image>
						</view>
						<!-- #endif -->
						<!-- 中间的输入框或者语音录入显示框 -->
						<view class="input-box-flex-grow">
							<view v-if="chatType === 'voice'" class="textArea-box">
								<scroll-view :scroll-y="true" :scroll-x="false" class="inputScroll" 
											 :show-scrollbar="true">
									<textarea style="text-indent:5upx;" auto-height="true"
										placeholder-style="color:#DDDDDD;" :cursor-spacing="10" :confirm-hold="true"
										confirm-type="send" :show-confirm-bar="false" :focus="inputFocusFlag"
										:auto-focus="false" :hold-keyboard="true" @blur="inputFocusFlag = false" 
										@focus="inputFocusFlag =true"
										@confirm="$noClicks(confirmSendText)" 
										v-model="sendStr" 
										:cursor="sendStr.length"
										:maxlength="-1">
									</textarea>
								</scroll-view>
							</view>
							<!-- #ifdef APP-PLUS -->
							<view v-if="chatType === 'keyboard'" class="voice_title">
								{{ voiceTitle }}
							</view>
							<!-- #endif -->
						</view>
						<view class="u-m-l-16 u-m-r-16" @touchend.prevent="$noClicks(sendMsg)">
							<u-button type="success" :custom-style="customSendBtnStyle">
								<text>发送</text>
							</u-button>
						</view>
					</view>
				</view>
			</view>
			
			<view>
				<view class="question-example u-flex u-row-center u-col-center"
						:style="'top:'+scrollViewHeight/2+'px'">
					<view @click="openExamplePop()">
						<view>查看</view>
						<view>示例</view>
					</view>
				</view>
				<view class="question-promto u-flex u-row-center u-col-center"
						:style="'top:'+(scrollViewHeight/2+60)+'px'">
					<view @click="openProPop()">
						<view>情景</view>
						<view>提问</view>
					</view>
				</view>

			</view>
		
		</view>
		<!-- 长按菜单 -->
		<chunLei-popups v-model="toolTipFlag" :popData="toolTipData" @tapPopup="tapPopup" :x="toolTipX" :y="toolTipY"
			direction="row" theme="dark" :dynamic="true">
		</chunLei-popups>
		<view v-if="exampleShow==true">
			<chat-gpt-example :show-flag="exampleShow" 
				@exampleToAnswer="exampleToAnswer"
				@closeRecordPop="closeRecordPop"></chat-gpt-example> 
		</view>
		<view v-if="proQuestionShow">
			<chatGptPro :show-flag="proQuestionShow"
				@proToAnswer="proToAnswer"
				@closeProPop="closeProPop"></chatGptPro> 
		</view>
		<u-modal v-model="updateShow"  width="80%" title="修改补充提示"
				:show-confirm-button="true" :show-cancel-button="true"
				confirm-text="补充提问" cancel-text="直接提问"
				mask-close-able
				@confirm="afterSend(1)" @cancel="afterSend(0)">
			<view class="u-p-20">
				<u-input v-model="updateContent"  type="textarea" :border="true" />
			</view>
		</u-modal>
	</view>
</template>

<script>
	import chatGptExample from '@/components/chat-gpt-example/chat-gpt-example.vue';
	import chatGptPro from '@/components/chat-gpt-example/chat-gpt-pro.vue';
	import chunLeiPopups from "@/components/chunLei-popups/chunLei-popups.vue";
	export default {
		components:{
			chunLeiPopups,chatGptExample,chatGptPro	
		},
		data() {
			return {
				tagStyle:{
					img:'width:22px;height:22px;position:relative;top:10rpx;',
					span:'margin:0px;padding:0px;font-size:30rpx',
				},
				customSendBtnStyle: { //发送按钮的自定义样式
					padding: '10rpx 30rpx',
					height:'70rpx',
				},
				notice:["openAi官方通道，可能会封，建议提供自己的apikey","偶尔可能根据您发送的内容，生成不正确的信息","AI暂时对2021年以后的信息和事情了解有限"],
				waiting:false,
				sendStr:'',
				currentAIAnswer:'',
				inputFocusFlag:false,
				messageList:[],
				AIReady:false,  //是否初始化
				noClick: true, //防止重复点击
				scrollIntoView:'',
				scrollTop: 0,
				scrollAnimation:false,
				scrollViewHeight:0,
				chatGroupId:'',
				chatType: 'voice', // 图标类型 'voice'语音 'keyboard'键盘
				voiceTitle:'按住 说话',
				exampleShow:false,
				proQuestionShow:false,
				updateShow:false,
				updateContent:"",
				toolTipFlag: false,
				toolTipData: [{
						id: 1,
						icon: '/static/image/chat/longTipIcon/copy.png',
						title: '复制',
						disabled: false
					},
					{
						id: 2,
						icon: '/static/image/chat/longTipIcon/tag.png',
						title: '收藏',
						disabled: false
					}
				],
				toolTipX: 0,
				toolTipY: 0,
				currentHandleMsg:'',
			}
		},
		
		watch: {
			//监听H5键盘是否拉起的高度
			inputFocusFlag: function(inputFocus) {
				let that = this;
				// #ifdef H5
				console.log("输入框焦点变化", inputFocus);
				if (inputFocus == true) {
					that.scrollViewHeight = that.$u.sys().windowHeight * 0.48;
					console.log("H5键盘打开", that.scrollViewHeight);
				} else {
					uni.hideKeyboard();
					let scrollViewHeight = this.windowHeight * 0.831;
					that.scrollViewHeight = scrollViewHeight;
					console.log("H5键盘收起", that.scrollViewHeight);
				}
				// #endif
			},
			/* 			
				//监听列表高度变化需要做的处理，主要发生在键盘弹出，表情抽屉，和功能性抽屉
				//监听到列表高度变化，保证最后一条信息不被键盘或者抽屉弹窗挡住
			*/
			scrollViewHeight(newVal, oldVal) {
				let that = this;
				//console.log("监听到列表高度变化，保证最后一条信息不被键盘或者抽屉弹窗挡住");
				if (that.messageList.length > 2) {
					that.scrollIntoView = "msg_" + that.messageList[that.messageList.length - 2].id;
					that.scrollAnimation = false;
					setTimeout(function() {
						that.scrollAnimation = true;
						that.scrollIntoView = "msg_" + that.messageList[that.messageList.length - 1].id;
					}, 500);
				}
			},
			
			messageList(talkList){
				let that=this;
				if(talkList.length>0){
					let newArr=JSON.parse(JSON.stringify(talkList));
					let newArrStr=JSON.stringify(newArr.reverse());
					uni.setStorageSync('chatgpt_'+this.vuex_userInfo.id,newArrStr);
					that.$nextTick(function(){
						let index= that.messageList.length-1;
						that.scrollIntoView="msg_"+that.messageList[index].id;
					})
				}
			}
		},
		
		created: function() {
			//计算页面高度布局
			this.windowHeight = this.$u.sys().windowHeight; //H5原始高度，H5键盘收起时会用到
			let scrollViewHeight = this.$u.sys().windowHeight * 0.831;
			this.scrollViewHeight = scrollViewHeight;
			this.scrollTop = scrollViewHeight;
		},
		onLoad() {
			let that=this;
			//实时监听后端socket信息
			uni.$on("handleAIMessage", function(aiAnswer) {
				let isEnd= aiAnswer.isEnd;
				let answer= aiAnswer.text;
				if(isEnd==true){
					console.log("====AI回复结束===",aiAnswer);
					let timestamp = new Date().getTime();
					let message = {
						"id": aiAnswer.id?aiAnswer.id:new Date().getTime() + "",
						"createTime": that.globalUtil.getTimeStr(timestamp),
						"chatGroupId": that.chatGroupId,
						"userId": "AI007",
						"meFlag": false,
						"userName": "AI",
						"userAvatar": "https://img.api.aa1.cn/2023/02/12/59c6fee6f7e66.png",
						"content": {'text': answer},
						"timestamp": timestamp,
						"showTimeFlag": false,
					}
					that.messageList.push(message);
					that.waiting=false;
					that.currentAIAnswer="";
					that.scrollTop=that.scrollTop+5;
				}else{
					//console.log("===回答中====",answer);
					setTimeout(function(){
						that.currentAIAnswer=that.currentAIAnswer+answer;
						that.scrollTop=that.scrollTop+5;
					},200);
				};
			});
			that.initChatGpt();
		},
		methods: {
			initChatGpt:function(){
				let that=this;
				let groupId="chatGpt_"+that.vuex_userInfo.id;
				that.chatGroupId=groupId;
				this.$u.api.chatgpt.startWSChatWithSSE({}).then(res => {
					if(res.code==200){
						that.AIReady=true;
						//console.log("历史会话记录",res);
					}
				});	
				let arr=[];
				let str =uni.getStorageSync("chatgpt_"+this.vuex_userInfo.id);
				if(str){
					that.messageList=JSON.parse(str).reverse();
				};
				that.$nextTick(function(){
					setTimeout(function(){
						that.scrollTop=that.scrollTop+1000;
					},200)
				})
			},
			loadMoreHistoryMsg:function(){
				
			},
			sendMsg: function() {
				let that = this;
				if(that.waiting==true){
					that.globalUtil.utilAlert("AI思考中，请勿骚操作");
					return;
				}
				if (that.sendStr.length < 1) {
					that.globalUtil.utilAlert("不能发送空字符串");
					return;
				}
				let contentObj = {
					"text": that.sendStr, //文本内容
				};
				let msgType=this.messageApi.MSG_TYPE.USER_MSG;
				let contentType=this.messageApi.CONTENT_TYPE.TEXT_CONTENT_TYPE;
				let timestamp = new Date().getTime();
				let message = {
					"id": new Date().getTime() + "",
					"createTime": that.globalUtil.getTimeStr(timestamp),
					"chatGroupId": that.chatGroupId,
					"userId": that.vuex_userInfo.id,
					"meFlag": true,
					"userName": that.vuex_userInfo.userName,
					"userAvatar": that.vuex_userInfo.avatar ? that.vuex_userInfo.avatar :
						"/static/image/default/default-user/default-user.png",
					'messageType': msgType,
					"contentType": contentType,
					"content": contentObj,
					"createTime": that.globalUtil.getTimeStr(timestamp),
					"timestamp": timestamp,
					"platFrom": this.messageApi.msgPlat,
					"showTimeFlag": true,
				}
				that.waiting=true;
				that.currentAIAnswer="";
				console.log("发送信息", message);
				this.globalWX.sendMessage(message, {
					complete: function(res) {
						console.log("=======已发送==========", res);
						that.inputFocusFlag=false;
						if (res == true) {
							that.messageList.push(message);
							that.sendStr="";
							uni.hideKeyboard();
						} else {
							that.globalUtil.utilAlert("网络故障，稍后重试！");
							that.waiting=false;
							uni.hideKeyboard();
							return;
						}
					}
				}, that.messageApi.BUSINESS_CODE.AI);
			},
			clear:function(tip){
				let that=this;
				uni.removeStorageSync('chatgpt_'+this.vuex_userInfo.id);
				this.$u.api.chatgpt.clearChatGpt({}).then(res => {
					if(res.code==200){
						that.messageList=[];
						if(tip){
							that.globalUtil.utilAlert(tip);
						}else{
							that.globalUtil.utilAlert("Reset Success");
						}
					}
				});
			},
			hideDrawer:function(){
				uni.hideKeyboard();
			},
			//切换语音或者键盘方式
			switchChatType(type) {
				let that = this;
				that.chatType = type;
			},
			//键盘确认发送
			confirmSendText: function(e) {
				let that = this;
				that.sendMsg();
			},
			//内容格式化
			parseTextContent: function(item) {
				let that=this;
				let contentObj=item.content;
				let msgStr = contentObj.text;
				let transText = this.globalUtil.transform(msgStr);
				return transText;
			},
			openExamplePop:function(){
				this.exampleShow=true;
			},
			exampleToAnswer:function(item){
				let that=this;
				let title=item.title;
				let content=item.content;
				that.exampleShow=false;
				this.$u.api.chatgpt.clearChatGpt({}).then(res => {
					if(res.code==200){
						that.messageList=[];
						that.updateContent=content;
						that.sendStr=content;
						that.updateShow=true;
					}
				});
			},
			closeRecordPop:function(){
				this.exampleShow=false;
			},
			afterSend:function(type){
				let that=this;
				if(type==1){
					that.sendStr=that.updateContent;
				};
				that.updateShow=false;
				that.updateContent="";
				that.sendMsg();
			},
			
			openProPop:function(){
				this.proQuestionShow=true;
			},
			closeProPop:function(){
				this.proQuestionShow=false;
			},
			proToAnswer:function(question){
				let that=this;
				that.proQuestionShow=false;
				console.log("增强提问内容",question);
				this.$u.api.chatgpt.clearChatGpt({}).then(res => {
					if(res.code==200){
						that.messageList=[];
						that.updateContent=question;
						that.sendStr=question;
						that.updateShow=true;
					}
				});
			},
			//操作项
			showToolTip: function(e, index) {
				let that = this;
				that.toolTipX = e.touches[0].clientX;
				that.toolTipY = e.touches[0].clientY;
				that.toolTipFlag = !that.toolTipFlag;
				that.currentHandleMsg = that.messageList[index];
			},
			tapPopup(e) {
				let that = this;
				if (e.title == "复制") {
					let content = that.currentHandleMsg.content;
					if (content) {
						let copyContent =content.text;
						that.globalUtil.uniCopy({
							content: copyContent,
							success: (res) => {
								uni.showToast({
									title: res,
									icon: 'none'
								})
							},
							error: (e) => {
								uni.showToast({
									title: e,
									icon: 'none',
									duration: 3000,
								})
							}
						})
					}
					that.toolTipFlag = false;
					return;
				}
				if (e.title == "收藏") {
					that.toolTipFlag = false;
				}
			},
			toAiCreateImage:function(){
				let that=this;
				this.$u.route("pages/tabbar/find/AI/ai-text-to-create-img/ai-text-to-create-img");
			}
		}
	}
</script>

<style lang="scss" scoped>
	.msg-container{
		padding: 20rpx;
	}
	
	.u-flex-reserve {
		flex-direction: row-reverse;
	}
	
	.u-text-reserve {
		text-align: left;
	}
	
	.chat-time {
		padding: 4rpx 0rpx;
		text-align: center;
		font-size: 28rpx;
		color: #909399;
	}
	
	.chat-container {
		width: 100%;
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		justify-items: flex-start;
		align-items: flex-start;
	}
	
	.chat-location-me {
		flex-direction: row-reverse;
		text-align: right;
	}
	
	.chat-icon-me {
		margin-right: 10rpx;
		border: 1rpx solid #f4f4f5 !important;
	}
	
	.chat-icon-container {
		margin-top: 12rpx;
	}
	
	.chat-icon {
		width: 80rpx;
		height: 80rpx;
		border-radius: 10rpx;
		background-color: #ffffff;
		border: 1rpx solid #71d5a1;
	}
	
	.chat-content-container {
		margin: 0rpx 15rpx;
		max-width: 70%;
	}
	
	.chat-user-name {
		font-size: 26rpx;
		color: #ffffff;
	}
	
	.chat-text-container {
		word-break: break-all;
		background-color: #ffffff;
		border-radius: 10rpx;
		padding: 20rpx 20rpx;
		margin-top: 5rpx;
		color: #000000;
	}
	
	.chat-text-container-me {
		background-color: #fff;
	}
	
	.footer-container {
		&-box {
			height: auto;
			min-height: calc(100vh - env(safe-area-inset-top) - 200rpx);
			box-sizing: content-box;
			position: relative;
			padding-bottom: 120rpx;
		}
	
		.input-box {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			box-sizing: content-box;
			z-index: 999;
			background: none !important;
	
			&-flex {
				display: flex;
				justify-content: flex-start;
				align-items: center;
				flex-wrap: nowrap;
				flex-direction: row;
				padding: 20rpx;
				box-sizing: border-box;
	
				image {
					width: 60rpx;
					height: 60rpx;
				}
	
				.icon_img {
					margin-right: 20rpx;
					background-color: #fff;
					border-radius: 30rpx;
				}
	
				.icon_btn_add {
					margin-left: 20rpx;
				}
	
				&-grow {
					flex-grow: 1;
	
					.content {
						box-sizing: border-box;
						background-color: #fff;
						height: 80rpx;
						padding: 0 20rpx;
						border-radius: 12rpx;
						font-size: 30rpx;
						caret-color: $uni-color-success;
					}
	
					.textArea-box {
						width: 100%;
						background-color: #FFFFFF;
						border-radius: 10upx;
						//padding-left: 30upx;
						min-height: 70upx;
						display: flex;
						align-items: center;
						color: #000000;	
						textarea {
							width: 100%;
						}
					}
	
					.inputScroll {
						max-height: 180upx;
					}
	
					/* 语音标题 */
					.voice_title {
						text-align: center;
						background-color: #ffffff;
						color: #000000;
						height: 80rpx;
						line-height: 80rpx;
						border-radius: 12rpx;
						font-weight: bold;
						font-size: 32rpx;
					}
				}
	
				.btn {
					margin-left: 20rpx;
					background-color: #FFFFFF;
					border: none;
				}
			}
		}
	}
	
	.question-example{
		position: fixed;
		width:100rpx;
		height:100rpx;
		right:10rpx;
		background-color: #f29100;
		border-radius: 50rpx;
		text-align: center;
	}
	.question-promto{
		position: fixed;
		width:100rpx;
		height:100rpx;
		right:10rpx;
		background-color: #2979ff;
		border-radius: 50rpx;
		text-align: center;
	}
	.ai-image{
		position: fixed;
		width:100rpx;
		height:100rpx;
		right:10rpx;
		background-color: #19be6b;
		border-radius: 50rpx;
		text-align: center;
	}
	
</style>
<style>
	page{
		background-image: url("/static/image/page-bg.png");
		width: 100%;
		height: 100%;
		background-size: cover;
		background-repeat: no-repeat;
		color: #fff;
	}
</style>